package com.aiwei.tdjk.controller;

import com.aiwei.tdjk.common.Constants;
import com.aiwei.tdjk.dto.request.BookingContainerPagerRequest;
import com.aiwei.tdjk.entity.*;
import com.aiwei.tdjk.enums.BookingContainerStatusEnum;
import com.aiwei.tdjk.enums.SaleOrderStatusEnum;
import com.aiwei.tdjk.service.*;
import com.aiwei.tdjk.utils.SnUtils;
import com.aiwei.tdjk.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping(value = "/admin/bookingContainer")
public class BookingContainerController extends BaseController {

	@Autowired
	private BookingContainerService bookingContainerService;

	@Autowired
	private SaleOrderHeaderService saleOrderHeaderService;

	@Autowired
	private DeliveryService deliveryService;

	@Autowired
	private DeliveryDetailService deliveryDetailService;

	@Autowired
	private CustomsHandbookUsedDetailService customsHandbookUsedDetailService;

	protected void setCommonData(Model model) {
		model.addAttribute("statusList", BookingContainerStatusEnum.values());
	}


	@RequestMapping(value = {"/list"}, method = RequestMethod.GET)
	public String list(BookingContainerPagerRequest request, Model model) {
		setCommonData(model);
		model.addAttribute("page", bookingContainerService.find(request));
		model.addAttribute("bookingContainer", request);
		return viewName("list");
	}

	@RequestMapping(value = {"/my"}, method = RequestMethod.GET)
	public String my(BookingContainerPagerRequest request, Model model) {
		User user = UserUtil.getUserFromSession();
		request.setBookingmanid(user.getId());
		model.addAttribute("page", bookingContainerService.find(request));
		model.addAttribute("bookingContainer", request);
		return viewName("list");
	}


	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String showCreateForm(Model model,Long ids) {
		model.addAttribute(Constants.OP_NAME, "新增");
		BookingContainer bookingContainer = new BookingContainer();
		SaleOrderHeader saleOrderHeader = saleOrderHeaderService.get(ids);
		bookingContainer.setSaleOrderCode(saleOrderHeader.getSaleordercode());

		model.addAttribute("m", bookingContainer);
		return viewName("editForm");
	}


	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(Model model, @Valid @ModelAttribute("m") BookingContainer m, BindingResult result,
			RedirectAttributes redirectAttributes) {
//		if (hasError(result))
//			return showCreateForm(model);
		m.setBookingCode("BC"+SnUtils.generate());
		User user = UserUtil.getUserFromSession();
		m.setBookingManId(user.getId());
		m.setBookingMan(user.getFullName());
		bookingContainerService.add(m);
		redirectAttributes.addFlashAttribute(Constants.MESSAGE, "新增成功");
		//修改订单的状态为已经订舱完成
		SaleOrderHeader saleOrderHeader = saleOrderHeaderService.getBySaleOrderCode(m.getSaleOrderCode());
		saleOrderHeader.setOrderstate(SaleOrderStatusEnum.booked.getCode().toString());
		saleOrderHeaderService.update(saleOrderHeader);
		return "redirect:/admin/saleOrderHeader/list";
	}


	@RequestMapping(value = "{id}/update", method = RequestMethod.GET)
	public String showUpdateForm(@PathVariable("id") Long id, Model model) {
		model.addAttribute(Constants.OP_NAME, "修改");
		model.addAttribute("m", bookingContainerService.get(id));
		return viewName("editForm");
	}

	/**
	 * 更新（仅仅在提交的状态下能够更新）
	 */
	@RequestMapping(value = "{id}/update", method = RequestMethod.POST)
	public String update(Model model, @Valid @ModelAttribute("m") BookingContainer m, BindingResult result,
						 RedirectAttributes redirectAttributes) {

		if (hasError(result)) {
			return showUpdateForm(m.getId(), model);
		}
		BookingContainer bookingContainer = bookingContainerService.get(m.getId());
		bookingContainer.getStatus();
		if (BookingContainerStatusEnum.apply.getCode().equals(bookingContainer.getStatus())){
			//修改基本信息
			bookingContainerService.update(m);
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, "修改成功");
		}else {
			redirectAttributes.addFlashAttribute(Constants.ERROR, "分货中不能修改，请联系跟单人员撤回，才能够修改");
		}

		return redirectToUrl("list");
	}


	@RequestMapping(value = "{id}/delete", method = RequestMethod.GET)
	public String showDeleteForm(@PathVariable("id") Long id, Model model) {

		model.addAttribute(Constants.OP_NAME, "删除");
		model.addAttribute("m", bookingContainerService.get(id));
		return viewName("editForm");
	}

	/**
	 * 删除（仅仅在提交的状态下能够删除）
	 */
	@RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
	public String delete(Model model, @Valid @ModelAttribute("m") BookingContainer m, BindingResult result,
						 RedirectAttributes redirectAttributes) {

		if (hasError(result)) {
			return showDeleteForm(m.getId(), model);
		}
		BookingContainer bookingContainer = bookingContainerService.get(m.getId());
		if (BookingContainerStatusEnum.apply.getCode().equals(bookingContainer.getStatus())){
			//修改g关联订单的状态为：未订舱
			SaleOrderHeader saleOrderHeader = saleOrderHeaderService.getBySaleOrderCode(bookingContainer.getSaleOrderCode());
			if (saleOrderHeader!=null){
				saleOrderHeader.setOrderstate(SaleOrderStatusEnum.notBooking.getCode().toString());
				saleOrderHeaderService.update(saleOrderHeader);
			}
			bookingContainerService.delete(m.getId());
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, "删除成功");
		}else{
			redirectAttributes.addFlashAttribute(Constants.ERROR, "分货中不能修改，请联系跟单人员撤回，才能够删除");
		}

		return redirectToUrl("list");
	}

	/**
	 * 撤回
	 */
	@RequestMapping(value = "/rollBack", method = RequestMethod.GET)
	public String rollBack(Model model, @RequestParam Long id,
						   RedirectAttributes redirectAttributes) {

		//todo 仅在仓管的范围内能够退回：分货中、分货未完成
		BookingContainer m = bookingContainerService.get(id);
		if (m.getStatus().equals(BookingContainerStatusEnum.delivering.getCode()) ||
				m.getStatus().equals(BookingContainerStatusEnum.deliveried.getCode())){
			//修改订舱的状态
			m.setStatus(BookingContainerStatusEnum.apply.getCode());
			bookingContainerService.update(m);
			//删除该订舱关联的分货单
			deliveryService.deleteDeliveryByBookingContainerId(m.getId());
			List<Delivery> deliveryList = deliveryService.getListBySaleOrderCode(m.getSaleOrderCode());
			deliveryDetailService.deleteListByDeliveryId(deliveryList);

			//删除商检
			List<CustomsHandbookUsedDetail> usedDetails = customsHandbookUsedDetailService.getListByDeliveryId(id);
			if (usedDetails!=null&&usedDetails.size()>0){
				for (CustomsHandbookUsedDetail usedDetail:usedDetails){
					customsHandbookUsedDetailService.delete(usedDetail.getId());
				}
			}

			redirectAttributes.addFlashAttribute(Constants.MESSAGE, "撤回成功");
			return redirectToUrl("list");
		}else {
			redirectAttributes.addFlashAttribute(Constants.ERROR, "不能够撤回");
			return redirectToUrl("list");
		}

	}



}
